package com.amadues.b2cmall.ware.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.amadues.b2cmall.ware.feign.ProductFeignService;
import com.amadues.common.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.amadues.common.utils.PageUtils;
import com.amadues.common.utils.Query;

import com.amadues.b2cmall.ware.dao.WareSkuDao;
import com.amadues.b2cmall.ware.entity.WareSkuEntity;
import com.amadues.b2cmall.ware.service.WareSkuService;
import org.springframework.util.StringUtils;


/**
 * 仓储sku服务
 *
 * @author Amadeus
 * @date 2020/11/24
 */
@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {

    @Autowired
    private WareSkuDao wareSkuDao;

    @Autowired
    private ProductFeignService productFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<WareSkuEntity> wrapper = new QueryWrapper<>();

        String skuId = (String) params.get("skuId");
        if (!StringUtils.isEmpty(skuId)) {
            wrapper.eq("sku_id", skuId);
        }

        String wareId = (String) params.get("wareId");
        if (!StringUtils.isEmpty(wareId)) {
            wrapper.eq("ware_id", wareId);
        }

        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void addStock(Long skuId, Long wareId, Integer skuNum) {
        //1.判断如果还没有这个库存记录就新增
        List<WareSkuEntity> wareSkuEntities = wareSkuDao.selectList(new QueryWrapper<WareSkuEntity>()
                .eq("sku_id", skuId).eq("ware_id", wareId));
        if (CollUtil.isEmpty(wareSkuEntities)) {
            WareSkuEntity skuEntity = new WareSkuEntity();
            skuEntity.setSkuId(skuId);
            skuEntity.setWareId(wareId);
            skuEntity.setStock(skuNum);
            //2.查询skuName进行冗余保存 如果失败 无需回滚
            try {
                R info = productFeignService.info(skuId);
                if (info.getCode() == 0) {
                    Map<String, Object> data = (Map<String, Object>) info.get("data");
                    skuEntity.setSkuName((String) data.get("skuName"));
                }
            } catch (Exception ignored) {

            }
            skuEntity.setStockLocked(0);
            //3.添加库存信息
            wareSkuDao.insert(skuEntity);
        } else {
            //4.否则更新库存信息
            wareSkuDao.addStock(skuId, wareId, skuNum);
        }

    }

}